package org.greenwire.islandharvester.helper;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class LoginHelper {
	
	private static Log logger = LogFactory.getLog(LoginHelper.class);
	
	private String loginUrl = "http://container.api.taobao.com/container?appkey=12029234";
	
	private WebClient client;
	
	public LoginHelper(WebClient client){
		this.client = client;
	}
	
	public boolean doLogin(String userName, String passwd){
		logger.info("Start logining for user " + userName);
		
		HtmlPage page;
		try {
			page = (HtmlPage)client.getPage(loginUrl);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return false;
		}
		HtmlForm loginForm = page.getFormByName("user_login");
		HtmlInput userNameInput = loginForm.getInputByName("TPL_username");
		userNameInput.setValueAttribute(userName);
		HtmlInput passwdInput = loginForm.getInputByName("TPL_password");
		passwdInput.setValueAttribute(passwd);
		HtmlInput submit = loginForm.getInputByName("Submit");
		try {
			submit.click();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return false;
		}
		
		logger.info("User " + userName + " login success!");
		
		return true;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}
}
